﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command.MenuaLL;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler.MenuaLL
{
    public class AddRoleMenusCommandHandler : IRequestHandler<AddRoleMenusCommand, ApiResult<int>>
    {
        IBaseReponsitory<RoleMenus> RoleMenus;

        public AddRoleMenusCommandHandler(IBaseReponsitory<RoleMenus> RoleMenus)
        {
            this.RoleMenus = RoleMenus;
        }

        public async Task<ApiResult<int>> Handle(AddRoleMenusCommand request, CancellationToken cancellationToken)
        {
            var Tst =await RoleMenus.GetQuery().FirstOrDefaultAsync(x => x.Role_Id == request.RoleMenus.Role_Id && !x.Menu_IsDels);
            if (Tst!=null)
            {
      
                Tst.Menu_Id = request.RoleMenus.Menu_Id;
                Tst.Role_Id = request.RoleMenus.Role_Id;
                await RoleMenus.UpdateAsync(Tst);
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "菜单修改成功",
                    Data = 0
                };
            }
            else
            {
                await RoleMenus.AddAsync(request.RoleMenus);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "添加角色菜单关系成功",
                    Data = 1
                };
            }



        }
    }
}
